function Music() {
    this.init();
}
(function () {
    var pages = [],
        panels = [],
        selectedItem = null;
    const scPlayer = new SoundCloudAudio('YOUR_CLIENT_ID')
    Music.prototype = {
        total: 70,
        pageSize:10,
        dataUrl:"http://songsearch.kugou.com/song_search_v2",
        playerUrl:"/songInfo",
        musicUrl: '',
        musicInfo: {},
        musicList: [],

        init:function () {
            var me = this;
            domUtils.on($G("J_searchName"), "keyup", function (event) {
                var e = window.event || event;
                if (e.keyCode == 13) {
                    me.dosearch();
                }
            });
            domUtils.on($G("J_searchBtn"), "click", function () {
                me.dosearch();
            });
        },
        callback: async function (data) {
            const _data = data.data
            var me = this
            me.data = _data.lists
            me.total = _data.total
            const html = await me._renderTemplate(_data.lists)
            $G('J_resultBar').innerHTML = html
        },
        dosearch: function () {
            var me = this;
            selectedItem = null;
            var key = $G('J_searchName').value;
            if (utils.trim(key) == "")return false;
            key = encodeURIComponent(key);
            me._sent(key);
        },
        doselect: async function (i) {
            var me = this;
            if (typeof i == 'object') {
                selectedItem = i;
            } else if (typeof i == 'number') {
                selectedItem = me.musicList[i];
            }
            const musicInfo = selectedItem.musicInfo
            me.musicUrl = musicInfo.url
            me.musicInfo = musicInfo
        },
        onpageclick:function (id) {
            var me = this;
            for (var i = 0; i < pages.length; i++) {
                $G(pages[i]).className = 'pageoff';
                $G(panels[i]).className = 'paneloff';
            }
            $G('page' + id).className = 'pageon';
            $G('panel' + id).className = 'panelon';
        },
        listenTest: async function (elem) {
            var me = this,
                view = $G('J_preview'),
                is_play_action = (elem.className == 'm-try'),
                old_trying = await me._getTryingElem();
            if (old_trying) {
                old_trying.className = 'm-try';
                view.innerHTML = '';
                scPlayer.pause()
            }
            if (is_play_action) {
                elem.className = 'm-trying';
                const html = await me._buildMusicHtml()
                view.innerHTML = html
            }
        },
        _sent:function (param) {
            var me = this;
            $G('J_resultBar').innerHTML = '<div class="loading"></div>';
            const url = me.dataUrl + '?keyword=' + param + '&page=1&pagesize=' + me.total +'&callback=music.callback&.r=' + Math.random()
            utils.loadFile(document, {
                src: url,
                tag:"script",
                type:"text/javascript",
                defer:"defer"
            });
        },
        _removeHtml: async function (str) {
            var reg = /<\s*\/?\s*[^>]*\s*>/gi;
            return str ? str.replace(reg, "") : '';
        },
        _getUrl:function (isTryListen = false) {
            return this.musicUrl
        },
        _getTryingElem: async function () {
            var s = $G('J_listPanel').getElementsByTagName('span');
            for (var i = 0; i < s.length; i++) {
                if (s[i].className == 'm-trying')
                    return s[i];
            }
            return null;
        },
        _buildMusicHtml: async function () {
            const musicInfo = selectedItem.musicInfo
            const me = this
            scPlayer.play({
                streamUrl: musicInfo.url
            }, _ => {
                scPlayer.play()
            })
            this.musicUrl = musicInfo.url
            me.musicInfo = musicInfo
            var html = ''
            return html
        },
        _byteLength:function (str) {
            return str.replace(/[^\u0000-\u007f]/g, "\u0061\u0061").length;
        },
        _getMaxText: async function (s) {
            var me = this;
            s = await me._removeHtml(s);
            if (me._byteLength(s) > 12)
                return s.substring(0, 5) + '...';
            if (!s) s = "&nbsp;";
            return s;
        },
        _rebuildData: async function (data) {
            var me = this,
            newData = [],
            d = me.pageSize,
            itembox,
            data1 = [];
            for (var i = 0; i < data.length; i++) {
                var param = '?cmd=playInfo&hash=' + data[i].FileHash + '&.r=' + Math.random()
                const url = me.playerUrl + param
                let _data = await me._getJSON(url)
                if (_data && _data.url) {
                    data[i]['musicInfo'] = _data
                    data1.push(data[i])
                    me.musicList.push(data[i])
                }
            }
            for (var i = 0; i < data1.length; i++) {
                if ((i + d) % d == 0) {
                    itembox = [];
                    newData.push(itembox)
                }
                itembox.push(data1[i])
            }
            return newData
        },
        _renderTemplate: async function (data) {
            var me = this;
            if (data.length == 0)return '<div class="empty">' + lang.emptyTxt + '</div>';
            data = await me._rebuildData(data);
            var s = [], p = [], t = [];
            s.push('<div id="J_listPanel" class="listPanel">');
            p.push('<div class="page">');
            for (var i = 0, tmpList; tmpList = data[i++];) {
                panels.push('panel' + i);
                pages.push('page' + i);
                if (i == 1) {
                    s.push('<div id="panel' + i + '" class="panelon">');
                    if (data.length != 1) {
                        t.push('<div id="page' + i + '" onclick="music.onpageclick(' + i + ')" class="pageon">' + (i ) + '</div>');
                    }
                } else {
                    s.push('<div id="panel' + i + '" class="paneloff">');
                    t.push('<div id="page' + i + '" onclick="music.onpageclick(' + i + ')" class="pageoff">' + (i ) + '</div>');
                }
                s.push('<div class="m-box">');
                s.push('<div class="m-h"><span class="m-t">' + lang.chapter + '</span><span class="m-s">' + lang.singer
                    + '</span><span class="m-z">' + lang.special + '</span><span class="m-try-t">' + lang.listenTest + '</span></div>');
                for (var j = 0, tmpObj; tmpObj = tmpList[j++];) {
                    s.push('<label for="radio-' + i + '-' + j + '" class="m-m">');
                    s.push('<input type="radio" id="radio-' + i + '-' + j + '" name="musicId" class="m-l" onclick="music.doselect(' + (me.pageSize * (i-1) + (j-1)) + ')"/>');
                    s.push('<span class="m-t">' + await me._getMaxText(tmpObj.SongName) + '</span>');
                    s.push('<span class="m-s">' + await me._getMaxText(tmpObj.SingerName) + '</span>');
                    s.push('<span class="m-z">' + await me._getMaxText(tmpObj.AlbumName) + '</span>');
                    s.push('<span class="m-try" onclick="music.doselect(' + (me.pageSize * (i-1) + (j-1)) + ');music.listenTest(this)"></span>');
                    s.push('</label>');
                }
                s.push('</div>');
                s.push('</div>');
            }
            t.reverse();
            p.push(t.join(''));
            s.push('</div>');
            p.push('</div>');
            const html = s.join('') + p.join('')
            return html
        },
        _get(url,cb = '') {
            var httpRequest = new XMLHttpRequest();
            httpRequest.open('GET', url, true);
            httpRequest.send();
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                    var json = httpRequest.responseText;//获取到json字符串，还需解析
                    if (typeof cb === 'function') {
                        cb(json)
                    } else {
                        sessionStorage.setItem('$_music_info', json)
                        return json
                    }
                }
            }
        },
        _getJSON(url) {
            return new Promise((resolve, reject) => {
                var httpRequest = new XMLHttpRequest()
                httpRequest.open('GET', url, true)
                httpRequest.send()
                httpRequest.onreadystatechange = function () {
                    if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                        var json = httpRequest.responseText
                        json = json ? JSON.parse(json) : ''
                        resolve(json)
                    }
                }
            } )
        },
        exec:function () {
            var me = this
            if (selectedItem == null)   return
            $G('J_preview').innerHTML = ""
            // editor.execCommand('music', {
            //     width: 400,
            //     height: 95,
            //     align: "center",
            //     url: me._getUrl(false)
            // })
            const html = '<audio id="my-audio" src="' + me._getUrl() + '" controls autoplay loop="false" />'
            editor.execCommand('inserthtml', html)
        }
    };
})();



